package javaroke.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javaroke.excepcion.DAOExcepcion;
import javaroke.modelo.Cliente;
import javaroke.modelo.Persona;
import javaroke.util.ConexionBD;

public class ClienteDAO extends BaseDAO {

	
	public Cliente ValidarAcceso(String correo, String clave) throws DAOExcepcion {
		Cliente vo = new Cliente();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			String query = "select idcliente, correo, clave, telefono, dni from cliente where correo =? and clave = ?";
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, correo);
			stmt.setString(2, clave);

			rs = stmt.executeQuery();
			if (rs == null){
				// insertar en persona
				// insertar en cliente
			}
			if (rs.next()) {
				vo.setIdcliente(rs.getInt("idcliente"));
				vo.setCorreo(rs.getString("correo"));
				vo.setClave(rs.getString("clave"));
				vo.setTelefono(rs.getString("telefono"));
				
				Persona persona = new Persona();
				persona.setDni(rs.getInt("dni"));
				
			}
			
			
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
			
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}
	
	public Cliente insertar(Cliente vo) throws DAOExcepcion {
		String query = "INSERT INTO cliente(correo, clave, telefono, dni) VALUES (?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);		
			stmt.setString(1, vo.getCorreo());
			stmt.setString(2, vo.getClave());
			stmt.setString(3, vo.getTelefono());
			stmt.setInt(4, vo.getDni().getDni());
			
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			
			// Obtener el ultimo id insertado a la BD
			int id = 0;
			query = "SELECT LAST_INSERT_ID()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			vo.setIdcliente(id);
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
			
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}
}
